package com.imooc.distributedlimiter;

import com.google.common.util.concurrent.RateLimiter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Description :
 * @Author : YTY
 * @Date : 2021-02-09 07:23
 */

@Slf4j
@RestController
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class LimiterController {

    private final LimiterService limiterService;

    private RateLimiter rateLimiter = RateLimiter.create(10);

    @GetMapping("guava")
    public void guava() {

        //创建可放2令牌的桶且每秒放2令牌，0.5秒放1令牌
//        RateLimiter rateLimiter = RateLimiter.create(2);
//
//        log.info("{}", rateLimiter.acquire(3));
//        log.info("{}", rateLimiter.acquire());
//        log.info("{}", rateLimiter.acquire());
//        log.info("{}", rateLimiter.acquire());

        boolean result = rateLimiter.tryAcquire();
        if (result) {
            // 扣库存，业务逻辑
            log.info("恭喜，秒杀成功！");
        } else {
            log.info("谢谢惠顾，这边滚~");
        }

    }

    @GetMapping("/sentinel")
    public String sentinel() {

        limiterService.process();
        return "sentinel";
    }

}
